<script setup lang="ts">
import {ref} from "vue";
import {usePlayStore} from '@/store/play-store.ts'
import {useRoute} from "vue-router";
import {updateMusicListCoverApi} from "@/api/list";

const playStore = usePlayStore()

const route = useRoute();
let listId = ref();
listId.value = route.params.listId

/**
 * @Description: 封面文件选择
 * @Author: sxgan
 * @Date: 2025/7/6 9:45
 **/
// 1. 使用明确的类型声明
const fileInput = ref<HTMLInputElement | null>(null);
const selectedFile = ref<File | null>(null);

const triggerFileInput = () => {
  // 2. 解决方案1：可选链操作符 (推荐)
  fileInput.value?.click();

  // 或者解决方案2：非空断言 (确保元素存在时使用)
  // fileInput.value!.click();
};
/**
 * @Description: 文件选择触发封面保存上传
 * @Author: sxgan
 * @Date: 2025/7/6 19:05
 **/
const handleFileChange = async (event: any) => {
  const files = event.target.files;
  if (files && files.length > 0) {
    const file = files[0];
    selectedFile.value = file;
    console.log('选中的文件:', file);

    // 检查播放列表数据
    if (!playStore.songList?.listInfo || !playStore.songList.listId) {
      console.error("播放列表信息不完整");
      // 这里可以添加用户提示，如: alert('请先选择播放列表');
      return;
    }

    try {
      // 调用API上传封面
      const res = await updateMusicListCoverApi(
          playStore.songList.listId,
          file
      );
      // 处理成功逻辑（例如更新UI）
      if (res.status === 200) {
        // 更新本地封面预览
        console.log(res)
        playStore.songList.listPic = res.data;
        playStore.setSongList(playStore.songList);
      } else {
        console.log("封面更新失败:", res.message);
      }
    } catch (e) {
      console.log("异常:");
    }
  }
};

/**
 * @Description: 点击保存修改歌单信息
 * @Author: sxgan
 * @Date: 2025/7/6 19:05
 **/
</script>

<template>
  <div class="list-edit">
    <h1>编辑歌单信息</h1>
    <div class="edit-content">
      <!-- 隐藏的文件输入 -->
      <input
          ref="fileInput"
          type="file"
          hidden="hidden"
          @change="handleFileChange"
      >
      <div class="content-left" @click="triggerFileInput">
        <div><img :src="playStore.songList.listPic" alt=""></div>
        <span>编辑封面</span>
      </div>
      <div class="content-right"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.list-edit {
  h1 {
    font-size: 3rem;
    line-height: 5rem;
    margin-left: 4rem;
    color: #ffffff;
  }

  .edit-content {
    display: flex;
    margin: 4rem;
    height: 23rem;

    .content-left {
      display: flex;
      flex-direction: column;

      img {
        width: 20rem;
        height: 20rem;
      }

      span {
        width: 20rem;
        height: 3rem;
        line-height: 3rem;
        text-align: center;
        font-size: 1.6rem;
        background: rgba(255, 255, 255, 0.15);
        color: #ffffff;
      }
    }

    .content-left:hover {
      span {
        color: #C4A3E6;
        background: rgba(255, 255, 255, 0.3);
      }
    }
  }
}
</style>